#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JilinJlskxjst77a8Policy(BaseTaxPolicySpider):
    name = 'jilin_jlsghhzrzyj_5cce_policy'
    
    province = '吉林省'
    city = '吉林市'
    county = ''
    park = ''
    source = '吉林市规划和自然资源局'
    url = 'http://ghzr.jlcity.gov.cn/zwgk/flfg/zcxwj/'
    
    def start_requests(self):
        for url in [
            self.url,
        ]:
            yield scrapy.Request(url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        print(response.url)
        prev_item = response.meta.get('item')
        if '系统繁忙,请稍后点击' in response.text:
            yield scrapy.Request(response.url, callback=self.parse_list, dont_filter=True, meta={'item': prev_item, 'is_next': False})
        elem_list = response.xpath(
            "//table//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//div//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//div//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9] | "
            "//table//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jsp' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            # print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下页' in response.text or '下一页' in response.text:
                totalpage = response.xpath(""".""").re_first(r"size:\s*(\d+),\s*current:")
                print('totalpage', totalpage)
                if totalpage:
                    for page in range(1, int(totalpage) + 1):
                        url = response.url + f'index_{page}.html'
                        yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
                else:
                    print(response.url)
            else:
                print(response.url)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("""string(//meta[@name='firstpublishedtime']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jilin_jlsghhzrzyj_5cce_policy".split())
